﻿using System.Collections.Generic;
using System.Text.RegularExpressions;
using System;
using GreenPark;
namespace Hanvon.KMS.Utils
{
    class HWParser
    {
        public delegate void OperationProgress2Message(uint total, uint done, string MsgUp, string MsgDown);

        public static List<RecordInfo> ParseToRcdInfoList(string devId, string retStr, OperationProgress2Message progress)
        {
            string pattern = "id=\"(?<id>[^\"]+)\"" + "\\s+name=\"(?<name>[^\"]*)\"" + "\\s+time=\"(?<time>[^\"]+)\"" + "(" + "\\s+photo=\"(?<photo>[^\"]+)\"" + ")*";

            MatchCollection mc = Regex.Matches(retStr, pattern);

            RecordInfo rcd;
            List<RecordInfo> rcdList = new List<RecordInfo>(mc.Count);
            uint total = (uint)mc.Count;
            uint done = 0;
            foreach (Match mRcd in mc)
            {
                if (progress != null)
                {
                    progress(total, done++, done.ToString() + "/" + total.ToString(), "Saving data...");
                }
                rcd = new RecordInfo();
                rcd.DevID = devId;
                DateTime temp;
                if (DateTime.TryParse(mRcd.Groups["time"].Value, out temp))
                {
                    rcd.RcdTime = temp;
                }
                else
                {
                    System.Windows.Forms.MessageBox.Show(string.Format("The format of the date or time is incorrect.", rcdList.Count + 1), "Hint", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                    continue;
                }


                rcd.EmployeeCode = mRcd.Groups["id"].Value;
                rcd.EmployeeName = mRcd.Groups["name"].Value;
                if (mRcd.Groups["photo"].Success)
                {
                    //string photoStr = mRcd.Groups["photo"].Value;
                    //Image im = Image.FromStream( new System.IO.MemoryStream( Convert.FromBase64String( photoStr ) ) );

                    rcd.ImageData = Convert.FromBase64String(mRcd.Groups["photo"].Value);
                }

                rcdList.Add(rcd);
            }
            if (progress != null)
            {
                progress(total, done, done.ToString() + "/" + total.ToString(), "Saving data...");
            }
            return rcdList;

        }
    }
}